package com.smarttest.portal.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.smarttest.portal.service.impl.DBUserAuthServiceImpl;

public class UserFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("OnlineFilter init>>>>>>>>>>>>>>>>>");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter)
			throws IOException, ServletException {
		// System.out.println("Enter UserFilter...");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		resp.setContentType("text/html;charset=UTF-8");
		String urlStr = req.getRequestURI();
		String loginUrl = req.getContextPath() + "/smarttest/login.html";
		String user = (String) req.getSession().getAttribute("name");
		if (user == null) {
			if ((urlStr.endsWith(".action") || urlStr.endsWith(".html") || urlStr.endsWith(".htm"))
					&& (!urlStr.endsWith("login.html") && !urlStr.endsWith("doLogin.action"))) {

				// Cookie[] cookies = req.getCookies();
				// if (cookies != null) {
				// for (int i = 0; i < cookies.length; i++) {
				// if (cookies[i].getName().equals("login")) {
				// String loginInfo = cookies[i].getValue();
				// String[] infos = loginInfo.split("&", 2);
				// String username = infos[0];
				// String password = infos[1];
				// User user = new User(username, password);
				// session.setAttribute("user", user);
				// filter.doFilter(req, resp);
				// return;
				// }
				// }
				// }
				// 判断是否为ajax请求
				if (req.getHeader("x-requested-with") != null
						&& req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
					resp.addHeader("sessionstatus", "timeOut");
					resp.addHeader("loginPath", loginUrl);
				} else {
					String str = "<script language='javascript'>alert('会话过期,请重新登录');" + "window.top.location.href='"
							+ loginUrl + "';</script>";
					response.setContentType("text/html;charset=UTF-8");// 解决中文乱码
					try {
						PrintWriter writer = response.getWriter();
						writer.write(str);
						writer.flush();
						writer.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
		/*		// 跳转至登录页面
				resp.sendRedirect(loginUrl);
				return;*/
			}
		}
		filter.doFilter(req, resp);
		// System.out.println("Exit UserFilter...");
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("OnlineFilter init>>>>>>>>>>>>>>>>>");
	}
}
